<template>
  <div class="app-container">
    <div class="couponSelectTop">
      <div class="couponSelect">
        <p>满减券</p>
        <span style="font-size:12px;color:#666;">例：满100元减20元</span>
        <span style="font-size:12px;color:#666;display:block;">便于合理控制活动成本</span>
        <el-button @click="fullReductions"
          type="primary"
          style="color:#fff;margin-top:15px">立即新建</el-button>
      </div>
      <div class="couponSelect">
        <p>折扣券</p>
        <span style="font-size:12px;color:#666;">例：满100元打9折</span>
        <span style="font-size:12px;color:#666;display:block;">提高店铺销量和客单价</span>
        <el-button @click="disCounts"
          type="primary"
          style="color:#fff;margin-top:15px">立即新建</el-button>
      </div>
      <!-- <div class="couponSelect">
        <p>菠萝币券</p>
        <span style="font-size:12px;color:#666;">例：500币券兑换500菠萝币</span>
        <span style="font-size:12px;color:#666;display:block;">直接兑换菠萝币</span>
        <el-button @click="coins"
          type="primary"
          style="color:#fff;margin-top:15px">立即新建</el-button>
      </div> -->
      <!--
      <div class="couponSelect">
        <p>兑换券</p>
        <span style="font-size:12px;color:#666;">例：兑换光子嫩肤套餐</span>
        <span style="font-size:12px;color:#666;display:block;">兑换商品、项目、套餐</span>
        <el-button @click="certificate"
          type="primary"
          style="color:#fff;margin-top:15px">立即新建</el-button>
      </div>
	  -->
    </div>
    <el-form class="formList"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="88px">
      <el-row>
        <el-form-item label="优惠券名称"
          prop="couponName">
          <el-input v-model="queryParams.couponName"
            placeholder="请输入优惠券名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="类型"
          prop="couponType">
          <el-select v-model="queryParams.couponType"
            placeholder="请选择类型"
            clearable
            size="small">
            <el-option v-for="dict in couponTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态"
          prop="couponStatus">
          <el-select v-model="queryParams.couponStatus"
            placeholder="请选择状态"
            clearable
            size="small">
            <el-option v-for="dict in couponStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery">搜索
          </el-button>
          <el-button icon="el-icon-refresh"
            size="mini"
            @click="resetQuery">重置
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['activity:coupon:add']">新增
        </el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['activity:coupon:edit']">修改
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['activity:coupon:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5"
        style="margin-left: 10px">
        <el-button type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['activity:coupon:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch"
        @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="divTable">
      <el-table border
        v-loading="loading"
        :data="couponList"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection"
          width="55"
          align="center" />
        <el-table-column label="图标"
          align="center"
          prop="couponIconUrl">
          <template slot-scope="scope">
            <el-image v-if="scope.row.couponIconUrl != null && scope.row.couponIconUrl != ''"
              slot="reference"
              :src="scope.row.couponIconUrl"
              class="image-rows"
              :preview-src-list="[scope.row.couponIconUrl]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="优惠券名称"
          align="center"
          prop="couponName"
          :show-overflow-tooltip="true"
          min-width="120">
          <template slot-scope="scope">
            <el-button size="mini"
              type="text"
              @click="handleShowDetail(scope.row)">{{ scope.row.couponName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="类型"
          align="center"
          prop="couponType"
          :formatter="couponTypeFormat" />
        <el-table-column label="优惠内容"
          align="center"
          prop="couponAmount"
          :show-overflow-tooltip="true"
          width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.amountStr }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="使用门槛" align="center" prop="baseAmount" :show-overflow-tooltip="true" /> -->
        <!-- <el-table-column label="领取开始时间" align="center" prop="getStartDate" width="160" sortable>
          <template slot-scope="scope">
            <span>{{
                parseTime(scope.row.getStartDate, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="到期类型"
          align="center"
          prop="expireType"
          :formatter="expireTypeFormat"
          width="100" />
        <el-table-column label="独立支付"
          align="center"
          prop="isExclusive"
          width="100">
          <template slot-scope="scope">
            <span>{{
              scope.row.isExclusive == '1'? '是': '否'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间"
          align="center"
          prop="startDate"
          width="160"
          sortable>
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.startDate, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间"
          align="center"
          prop="endDate"
          width="160"
          sortable>
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.endDate, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态"
          align="center"
          prop="couponStatus"
          :formatter="couponStatusFormat">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.couponStatus"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="发放总量"
          align="center"
          prop="couponNums"
          :show-overflow-tooltip="true" />
        <el-table-column label="领用数量"
          align="center"
          prop="useNums"
          :show-overflow-tooltip="true"
          width="100" />
        <el-table-column label="描述"
          align="center"
          prop="couponDesc"
          :show-overflow-tooltip="true"
          min-width="120" />
        <el-table-column label="更新人"
          align="center"
          prop="updateName"
          width="120" />
        <el-table-column label="更新时间"
          align="center"
          prop="updateTime"
          width="160"
          sortable>
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="120"
          fixed="right">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleShowDetail(scope.row)"
              v-hasPermi="['activity:coupon:query']">查看
            </el-button> -->
            <el-button type="text"
              icon="el-icon-edit"
              @click="toOpenSetRule(scope.row)">新增规则</el-button>
            <el-button type="text"
              icon="el-icon-edit"
              @click="toOpenSet(scope.row)">发送</el-button>

            <el-button type="text"
              @click="toOpenViewRule(scope.row)">查看规则</el-button>
            <el-button size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['activity:coupon:edit']">修改
            </el-button>
            <el-button v-if="scope.row.couponStatus == '0'"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['activity:coupon:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改优惠券信息对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="优惠券类型" prop="couponType">
          <el-select v-model="form.couponType" placeholder="请选择类型" @change="changeType">
            <el-option v-for="dict in couponTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片">
          <image-list :imageStr.sync="form.couponIconUrl" size="1" />
        </el-form-item>
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠金额/折扣率" prop="couponAmount">
          <el-input v-model="form.couponAmount" placeholder="请输入优惠金额/折扣率" />
        </el-form-item>
        <el-form-item label="使用门槛" prop="baseAmount">
          <el-input v-model="form.baseAmount" placeholder="请输入使用门槛" />
        </el-form-item>
        <el-form-item label="领取开始时间" prop="getStartDate">
          <el-date-picker clearable size="small" v-model="form.getStartDate" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择领取开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期类型" prop="expireType">
          <el-select v-model="form.expireType" placeholder="请选择到期类型">
            <el-option v-for="dict in expireTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker clearable size="small" v-model="form.startDate" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker clearable size="small" v-model="form.endDate" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效时长" prop="expireDays">
          <el-input v-model="form.expireDays" placeholder="请输入有效时长" />
        </el-form-item>
        <el-form-item label="适用商品" prop="couponProUids">
          <el-input v-model="form.couponProUids" placeholder="请输入适用商品" />
        </el-form-item>
        <el-form-item label="发放总量" prop="couponNums">
          <el-input v-model="form.couponNums" placeholder="请输入发放总量" />
        </el-form-item>
        <el-form-item label="描述" prop="couponDesc">
          <el-input v-model="form.couponDesc" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="排序" prop="dataPriority">
          <el-input v-model="form.dataPriority" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->

    <el-dialog title="发放规则设置"
      :visible.sync="dialogVisible"
      width="620px"
      @close="resetSendRuleForm">
      <el-form ref="couponRule"
        label-width="80px"
        size="small"
        :rules="rules"
        :model="ruleForm">
        <el-form-item label="发放时间"
          prop="sendDate">
          <el-date-picker v-model="ruleForm.sendDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发放规则"
          prop="ruleType"
          v-if="dialogVisible">

          <el-radio-group v-model="ruleForm.ruleType">

            <div style="margin-top: 6px">
              <el-radio label="time">
                定时发送
                <div class="to-send-time"
                  v-if="ruleForm.ruleType == 'time'">
                  <span class="to-send-time-label">发放时间</span>
                  <el-time-select v-model="ruleForm.sendTime"
                    style="width: 215px"
                    :picker-options="{
                    start: '00:00',
                    step: '00:15',
                    end: '23:59'
                  }">
                  </el-time-select>
                </div>
              </el-radio>

            </div>
            <div class="item-radio-style">
              <el-radio label="register">用户注册时发送</el-radio>
            </div>
            <div class="item-radio-style">
              <el-radio label="memberLevel">
                会员等级
                <el-select v-model="ruleForm.memberLevelIds"
                  multiple
                  placeholder="请选择"
                  clearable
                  style="margin-left: 6px">
                  <el-option v-for="item in memberLevel"
                    :key="item.levelId"
                    :label="item.levelName"
                    :value="item.levelId">
                  </el-option>
                </el-select>

                <div class="to-send-time"
                  v-if="ruleForm.ruleType == 'memberLevel'">
                  <span class="to-send-time-label">发放时间</span>
                  <el-time-select v-model="ruleForm.sendTime"
                    style="width: 215px"
                    :picker-options="{
                    start: '00:00',
                    step: '00:15',
                    end: '23:59'
                  }">
                  </el-time-select>
                </div>

              </el-radio>
            </div>
            <!--
            <div class="item-radio-style">
              <el-radio label="common">通用 </el-radio>
            </div>
            -->
            <div class="item-radio-style">
              <el-radio label="birthday">用户生日当天发放</el-radio>
            </div>
            <!--
            <div class="item-radio-style">
              <el-radio label="buy">用户购买</el-radio>
              <div class="user-buy-set"
                v-if="ruleForm.ruleType == 'buy'">
                <span class="user-buy-set-label">价格设置</span>
                <div class="user-buy-set-box">
                  <div class="item-user-price-set">
                    <el-input v-model="ruleForm.price"
                      style="width: 80px;margin-right: 8px"
                      type="number"></el-input>元
                  </div>
                  <div class="item-user-price-set">
                    <el-input v-model="ruleForm.boluoHua"
                      style="width: 80px;margin-right: 8px"
                      type="number"></el-input>
                    菠萝派（如不设置则表示可直接用人民币购买）
                  </div>
                </div>
              </div>
            </div>
            -->
            <!--
            <div class="item-radio-style">
              <el-radio label="gift">放入美容师赠送包</el-radio>
            </div>
            -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放地区"
          prop="areaList">
          <el-cascader :options="areaOptions"
            :props="areaProps"
            collapse-tags
            clearable
            v-model="ruleForm.areaList"></el-cascader>
        </el-form-item>
        <el-form-item label="发放方式"
          prop="sendRule">
          <el-radio-group v-model="ruleForm.sendRule">
            <div class="item-radio-style">
              <el-radio label="auto">自动发放</el-radio>
            </div>
            <!--
            <div class="item-radio-style">
              <el-radio label="get">会员自领取</el-radio>
            </div>
            -->
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer"
        class="dialog-footer">
        <el-button @click="resetSendRuleForm">取 消</el-button>
        <el-button type="primary"
          @click="toSubmitSendRule">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看发放规则 -->
    <el-dialog title="发放规则设置"
      :visible.sync="viewRuleOpen"
      width="800px"
      append-to-body
      @close="toCloseViewRule">
      <div class="rule_list">
        <div class="item_rule_box"
          v-for="(item, idx) in  viewRuleLists"
          :key="idx">
          <div class="item_rule_top">
            <div class="item_rule_label">规则{{ idx + 1 }}</div>
            <el-button type="text"
              @click="toEditRule(item)">修改</el-button>
          </div>
          <div class="item_rule_content">
            <div class="item_rule_content_show">
              <div class="item_rule_content_label">发放时间</div>
              <div class="item_rule_content_desc">{{ item.startTime }} 至 {{ item.endTime }}</div>
            </div>
            <div class="item_rule_content_show">
              <div class="item_rule_content_label">发放规则</div>
              <div class="item_rule_content_desc"
                v-html="showSendRuleText(item)"></div>
            </div>
            <div class="item_rule_content_show">
              <div class="item_rule_content_label">发放省份</div>
              <div class="item_rule_content_desc">{{ item.province }}</div>
            </div>
            <div class="item_rule_content_show">
              <div class="item_rule_content_label">发放城市</div>
              <div class="item_rule_content_desc">{{ item.city }}</div>
            </div>
            <div class="item_rule_content_show">
              <div class="item_rule_content_label">发放方式</div>
              <div class="item_rule_content_desc">{{ item.sendRule == 'auto' ? '自动发放' : '会员自领取' }}</div>
            </div>
          </div>
        </div>
        <div v-if="viewRuleLists.length == 0"
          class="rule-list-blank">暂无发放规则</div>
      </div>

      <div slot="footer"
        class="dialog-footer"
        style="text-align: center">
        <el-button type="primary"
          @click="dialogVisible = true">添加规则</el-button>
        <el-button @click="toCloseViewRule">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看优惠券信息对话框 -->
    <el-dialog :title="viewTitle"
      :visible.sync="viewOpen"
      width="1000px"
      append-to-body>
      <couponView v-if="couponVo"
        :couponVo="couponVo"></couponView>
    </el-dialog>

    <!-- 发送优惠券 -->
    <el-dialog title="发送优惠券"
      :visible.sync="dialogSendCoustomer"
      width="500px"
      append-to-body>
      <el-form :model="refForm"
        label-width="110px"
        ref="refForm"
        size="small">
        <el-form-item label="客户搜索">
          <el-select v-model="customerSearch"
            ref="agentSelect"
            filterable
            remote
            reserve-keyword
            style="width: 100%"
            placeholder="请输入手机号码或用户名称"
            :remote-method="remoteMethod"
            :loading="selectLoading"
            @change="changeSelectPhone"
            @hook:mounted="cancalReadOnly"
            @visible-change="cancalReadOnly"
            @keyup.enter.native="handleSearchUser">
            <el-option v-for="item in phoneList"
              :key="item.customerUid"
              :label="`${item.phone} (${item.customerName})`"
              :value="item.customerUid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码"
          prop="phone">
          <el-input label
            v-model="refForm.phone"
            disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名"
          prop="cusotmerName">
          <el-input disabled
            v-model="refForm.cusotmerName"></el-input>
        </el-form-item>
        <el-form-item label="发券数量"
          prop="sendNumber">
          <el-input v-model="refForm.sendNumber"
            @input="sendCouponLimit"
            @blur="sendCouponLimitBlur"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button @click="closeDialogBox">取消</el-button>
        <el-button @click="toSubmitSave"
          type="primary">确定发送</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
  updateStatus,
  getCouponRule,
  addCouponRule,
  updateCouponRule,
  getMemberLevel,
  getRegionList,
  addSendRule,
  viewRuleList,
  editSendRule,
  dialogSend,
  sendCoupon
} from "@/api/activity/coupon";
import {
  phoneGetUser,
} from "@/api/service/makePlan";
// import couponView from "./view";
import { onInput } from "@/utils/util";


import imageList from "@/components/ImageUpload/imageList";

export default {
  name: "Coupon",
  components: {
    // couponView,
    imageList,
  },
  data () {
    return {

      timeValue: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券信息表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      //查看详细标题
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      //是否显示查看详细弹出层
      viewOpen: false,
      //查看详细数据
      showData: [],
      // 类型字典
      couponTypeOptions: [],
      // 到期类型字典
      expireTypeOptions: [],
      // 状态字典
      couponStatusOptions: [],
      //优惠券信息
      couponVo: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponName: null,
        couponType: null,
        getStartDate: null,
        expireType: null,
        startDate: null,
        endDate: null,
        couponStatus: null,
        updateName: null,
      },
      phoneList: [],
      // 表单参数

      dialogVisible: false,
      ruleForm: {
        sendDate: [],
        startTime: '',
        endTime: '',
        ruleType: '',
        sendTime: '',
        lastFinishSendTime: '',
        memberLevelIds: [],
        memberLevelNames: '',
        sendRule: '',
        boluoHua: '',
        price: '',
        areaList: [],
        province: '',
        city: ''
      },
      isEditLoad: true,
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      memberLevel: [],
      areaProps: { multiple: true, expandTrigger: 'hover', value: 'label' },
      areaOptions: [],
      rules: {
        sendDate: [
          { type: 'array', required: true, message: '请选择发放日期', trigger: 'change' }
        ],
        ruleType: [
          { required: true, message: '请选择发放规则', trigger: 'change' }
        ],
        areaList: [
          { type: 'array', required: false, message: '请选择发放地区', trigger: 'change' }
        ],
        sendRule: [
          { required: true, message: '请选择发放方式', trigger: 'change' }
        ]
      },
      viewRuleOpen: false,
      viewRuleLists: [],
      viewRuleRow: {},
      refForm: {
        sendNumber: 1
      },
      dialogSendCoustomer: false,
      customerSearch: null,
      selectLoading: false,
      form: {},
      couponRule: {},
      userQuery: ''
    };
  },
  created () {
    this.getList();
    this.getDicts("activity_coupon_type").then((response) => {
      this.couponTypeOptions = response.data;
    });
    this.getDicts("activity_expire_type").then((response) => {
      this.expireTypeOptions = response.data;
    });
    this.getDicts("activity_data_status").then((response) => {
      this.couponStatusOptions = response.data;
    });
    this.togGetMemberList()
    this.toGetRegionList()
  },
  //监听路由
  watch: {
    ['ruleForm.ruleType'] () {
      if (!this.isEditLoad) {
        this.isEditLoad = true
        return
      }
      this.ruleForm.sendTime = ''
      this.ruleForm.memberLevelIds = []
      this.ruleForm.memberLevelNames = ''
      this.ruleForm.sendRule = ''
      this.ruleForm.boluoHua = ''
      this.ruleForm.price = ''
    },
    $route (to, from) {
      //from 从哪来
      //to //到哪去
      let path = from.path;
      if ("/FullReduction/data/" == path || "/Discount/data/" == path) {
        //刷新页面
        this.getList();
      } else {
        let index = path.lastIndexOf("/");
        if (index > -1) {
          path = path.substr(0, index);
          console.log(path)

          if ("/FullReduction/data" == path || "/Discount/data" == path) {
            //刷新页面
            this.getList();
          }
        }
      }
    }
  },
  methods: {
    onInput,
    sendCouponLimit () {
      if (this.refForm.sendNumber < 0) {
        this.refForm.sendNumber = 1
      }
      if (this.refForm.sendNumber > 100) {
        this.refForm.sendNumber = 100
      }
      this.refForm.sendNumber = this.onInput(this.refForm.sendNumber + '', 0)
    },
    sendCouponLimitBlur () {
      if (this.refForm.sendNumber < 1) {
        this.refForm.sendNumber = 1
      }
      if (this.refForm.sendNumber > 100) {
        this.refForm.sendNumber = 100
      }
    },
    cancalReadOnly (onOff) {
      this.$nextTick(() => {
        if (!onOff) {
          const Selects = this.$refs
          if (Selects.agentSelect) {
            const input = Selects.agentSelect.$el.querySelector('.el-input__inner')
            input.removeAttribute('readonly')
          }
        }
      })
    },
    //
    showSendRuleText (item) {
      let type = item.ruleType
      if (type == 'time') {
        return `按照时间进行发放 \&#12288;\&#12288; 发放时间: ${item.sendTime}`
      } else if (type == 'register') {
        return `用户注册时发放`
      } else if (type == 'memberLevel') {
        return `会员等级 ${item.memberLevelNames} \&#12288;\&#12288; 发放时间: ${item.sendTime}`
      } else if (type == 'birthday') {
        return `用户生日当天发放`
      } else if (type == 'common') {
        return `通用 `
      } else if (type == 'buy') {
        return `用户购买 \&#12288;\&#12288; 价格 ${item.price}元 \&#12288; ${item.boluoHua ? item.boluoHua + '菠萝派' : ''} `
      } else if (type == 'gift') {
        return `放入美容师赠送包`
      }
      return ''
    },
    toOpenSetRule (row) {
      this.dialogVisible = true
      this.viewRuleRow = row
    },
    toOpenSet (row) {
      this.refForm = {
        sendNumber: 1
      }
      this.customerSearch = null
      this.phoneList = []
      this.dialogSendCoustomer = true
      this.viewRuleRow = row

    },
    closeDialogBox () {
      this.dialogSendCoustomer = false
    },
    toSubmitSave () {
      let data = {
        customerUid: this.refForm.customerId,
        couponUid: this.viewRuleRow.couponUid,
        sendNumber: this.refForm.sendNumber
      }
      if (!data.customerUid) {
        this.$message.error('请选择用户');
        return;
      }
      sendCoupon(data).then(response => {
        this.msgSuccess("操作成功");
        this.dialogSendCoustomer = false
      });
    },
    handleSearchUser () {
      this.selectLoading = true;
      setTimeout(() => {
        phoneGetUser({ name: this.userQuery })
          .then(res => {
            this.selectLoading = false;
            this.phoneList = res.data
          })
          .catch(() => { })
      }, 200);
    },
    remoteMethod (query) {
      if (query !== '') {
        this.userQuery = query
      } else {
        // this.options = [];
      }
    },
    async changeSelectPhone (uid) {
      this.phoneList.forEach(item => {
        if (item.customerUid == uid) {
          this.refForm.customerId = item.customerUid
          this.refForm.cusotmerName = item.customerName
          this.refForm.phone = item.phone
          this.refForm.sendNumber = 1
        }
      })
    },
    // 查询会员等级
    togGetMemberList () {
      getMemberLevel().then((response) => {
        this.memberLevel = response.rows;
      });
    },
    // 查询省市区
    toGetRegionList () {
      getRegionList().then((response) => {
        this.areaOptions = response.data;
      });
    },
    // 发放规则提交
    toSubmitSendRule () {
      this.$refs['couponRule'].validate((valid) => {
        if (valid) {
          if (this.ruleForm.sendDate.length > 0) {
            this.ruleForm.startTime = this.ruleForm.sendDate[0]
            this.ruleForm.endTime = this.ruleForm.sendDate[1]
          }

          let memberLevelIds = ''
          if (this.ruleForm.memberLevelIds.length > 0) {
            let strs = []
            this.memberLevel.forEach(item => {
              if (this.ruleForm.memberLevelIds.indexOf(item.levelId) > -1) {
                strs.push(item.levelName)
              }
            })
            this.ruleForm.memberLevelNames = strs.join(',')
            memberLevelIds = this.ruleForm.memberLevelIds.join(',')
          } else {
            memberLevelIds = ""
          }

          let provinceList = [], cityList = []
          this.ruleForm.areaList.forEach(item => {
            if (provinceList.indexOf(item[0]) < 0) {
              provinceList.push(item[0])
            }
            if (cityList.indexOf(item[1]) < 0) {
              cityList.push(item[1])
            }
          })
          console.log(this.ruleForm)
          this.ruleForm.province = provinceList.join(',')
          this.ruleForm.city = cityList.join(',')
          if (this.ruleForm.ruleType == 'time') {
            if (!this.ruleForm.sendTime) {
              this.msgError('请选择发送时间')
              return
            }
          } else if (this.ruleForm.ruleType == 'memberLevel') {
            if (!memberLevelIds) {
              this.msgError('请选择会员等级')
              return
            }
            if (!this.ruleForm.sendTime) {
              this.msgError('请选择发送时间')
              return
            }
          } else if (this.ruleForm.ruleType == 'buy') {
            if (!this.ruleForm.price) {
              this.msgError('请设置购买价格')
              return
            }
          }
          this.ruleForm.couponId = this.viewRuleRow.couponUid

          // addSendRule
          this.$confirm('确认提交规则?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.ruleForm.ruleId) {
              // delete this.ruleForm.sendDate
              // delete this.ruleForm.areaList
              editSendRule({
                ...this.ruleForm,
                memberLevelIds
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });
                this.resetSendRuleForm()
                this.toGetRuleList()

              })
            } else {
              addSendRule({
                ...this.ruleForm,
                memberLevelIds
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });

                this.resetSendRuleForm()
                this.toGetRuleList()
              })
            }
          }).catch(() => {

          });

        }
      })
    },
    resetSendRuleForm () {
      this.dialogVisible = false
      this.$refs['couponRule'].resetFields();
      this.ruleForm = {
        sendDate: [],
        startTime: '',
        endTime: '',
        ruleType: '',
        sendTime: '',
        lastFinishSendTime: '',
        memberLevelIds: [],
        memberLevelNames: '',
        sendRule: '',
        boluoHua: '',
        price: '',
        areaList: [],
        province: '',
        city: ''
      }
    },
    // 查看规则
    toOpenViewRule (row) {
      this.viewRuleOpen = true
      this.viewRuleRow = row
      this.toGetRuleList()
    },
    toGetRuleList () {
      viewRuleList({ couponId: this.viewRuleRow.couponUid }).then(res => {
        this.viewRuleLists = res.rows
      })
    },
    toCloseViewRule () {
      this.viewRuleOpen = false
      this.viewRuleLists = []
      this.viewRuleRow = {}
    },
    toEditRule (row) {
      let list = [], provinceList = row.province.split(','), cityList = row.city.split(',')
      provinceList.forEach(item => {
        cityList.forEach(val => {
          list.push([item, val])
        })
      })
      let memberIds = row.memberLevelIds.split(','), ids = []
      memberIds.forEach(item => {
        if (item) {
          ids.push(parseFloat(item))
        }
      })

      this.ruleForm = {
        ruleId: row.ruleId,
        sendDate: [row.startTime, row.endTime],
        startTime: row.startTime,
        endTime: row.endTime,
        ruleType: row.ruleType,
        sendTime: row.sendTime,
        lastFinishSendTime: row.lastFinishSendTime,
        memberLevelIds: ids,
        sendRule: row.sendRule,
        boluoHua: row.boluoHua,
        price: row.price,
        areaList: list,
        province: row.province,
        city: row.city
      }
      this.isEditLoad = false
      this.dialogVisible = true
    },
    //添加满减劵
    fullReductions () {
      this.$router.push("/FullReduction/data/")
    },
    //添加菠萝币劵
    coins () {
      this.$router.push("/ExchangeCoins/data/")
    },
    //添加兑换劵
    certificate () {
      this.$router.push("/ExchangeCertificate/data/")
    },
    //添加折扣劵
    disCounts () {
      this.$router.push("/Discount/data/")
    },
    /** 查询优惠券信息列表 */
    getList () {
      this.loading = true;
      listCoupon(this.queryParams).then((response) => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 类型字典翻译
    couponTypeFormat (row, column) {
      return this.selectDictLabel(this.couponTypeOptions, row.couponType);
    },
    // 到期类型字典翻译
    expireTypeFormat (row, column) {
      return this.selectDictLabel(this.expireTypeOptions, row.expireType);
    },
    // 状态字典翻译
    couponStatusFormat (row, column) {
      return this.selectDictLabel(this.couponStatusOptions, row.couponStatus);
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        couponId: null,
        platformUid: null,
        couponName: null,
        couponType: null,
        couponIconUrl: null,
        couponAmount: null,
        baseAmount: null,
        getStartDate: null,
        expireType: null,
        startDate: null,
        endDate: null,
        expireDays: null,
        couponProUids: null,
        couponStatus: null,
        couponNums: null,
        useNums: null,
        couponDesc: null,
        dataPriority: null,
        updateUid: null,
        updateTime: null,
        createTime: null,
        createUid: null,
        createName: null,
        updateName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.couponUid);
      this.names = selection.map(item => item.couponName)
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.couponStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加优惠券信息";
    },
    /** 查看详情按钮操作 **/
    handleShowDetail (row) {
      let couponUid = row.couponUid || this.ids;
      let couponType = row.couponType;
      if (couponType && couponType == '1') {
        this.$router.push("/FullReduction/view/" + couponUid)
      } else if (couponType && couponType == '2') {
        this.$router.push("/Discount/view/" + couponUid)
      } else if (couponType && couponType == '3') {
        this.$router.push("/ExchangeCoins/view/" + couponUid)
      } else if (couponType && couponType == '4') {
        this.$router.push("/ExchangeCertificate/view/" + couponUid)
      }
      // this.couponVo = null;
      // const couponUid = row.couponUid;
      // getCoupon(couponUid).then((response) =>{
      //   this.couponVo = response.data;
      //   this.viewOpen = true;
      //   this.viewTitle = "优惠券详情";
      // })
    },
    handCloseDetail () {
      this.viewOpen = false;
      this.showData = [];
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      let couponUid = row.couponUid || this.ids;
      let couponType = row.couponType;
      if (couponType && couponType == '1') {
        this.$router.push("/FullReduction/data/" + couponUid)
      } else if (couponType && couponType == '2') {
        this.$router.push("/Discount/data/" + couponUid)
      } else if (couponType && couponType == '3') {
        this.$router.push("/ExchangeCoins/data/" + couponUid)
      } else if (couponType && couponType == '4') {
        this.$router.push("/ExchangeCertificate/data/" + couponUid)
      }
    },

    submitRule () {
      addCouponRule(this.couponRule).then((response) => {
        this.msgSuccess("新增发放规则成功");
        this.open = false;
        this.getList();
      });
    },

    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.couponUid != null) {
            updateCoupon(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.couponStatus === "0" ? "无效" : "有效";
      this.$confirm('确定要把优惠券名称为"' + row.couponName + '",设为' + text + '吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return updateStatus(row.couponUid, row.couponStatus);
      }).then(() => {

        this.msgSuccess("操作成功");
        this.getList();
      }).catch(function () {
        row.couponStatus = row.couponStatus === "0" ? "1" : "0";
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const couponUids = row.couponUid || this.ids;
      const names = row.couponName || this.names;
      this.$confirm(
        '是否确认删除优惠券信息名称为"' + names + '"的数据项?',
        "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
      )
        .then(function () {
          return delCoupon(couponUids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "/prod-api/activity/coupon/export", {
        ...this.queryParams,
      },
        `activity_coupon.xlsx`
      );
    },
    changeType (v) {
      this.form = {
        couponAmount: null,
        baseAmount: null,
        getStartDate: null,
        expireType: null,
        startDate: null,
        endDate: null,
        expireDays: null,
        couponProUids: null,
        couponStatus: null,
        couponNums: null,
        useNums: null,
        couponDesc: null,
        dataPriority: null,
        updateUid: null,
        updateTime: null,
        createTime: null,
        createUid: null,
        createName: null,
        updateName: null,
      };
    },
  },
};
</script>
<style lang="less" scoped>
.couponSelectTop {
  width: 100%;
  height: 100%;
  display: flex;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;

  .couponSelect {
    width: 263px;
    height: 150px;
    background: #fff;
    margin-right: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    box-shadow: 5px 5px 10px 6px rgba(0, 0, 0, 0.03);
  }

  .image-rows {
    width: 60px;
    height: 60px;
  }
}

.item-radio-style {
  margin-top: 16px;
}

.to-send-time {
  padding-left: 26px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #333;
  margin-top: 20px;

  .to-send-time-label {
    margin-right: 10px;
  }
}

.user-buy-set {
  padding-left: 26px;
  margin-top: 20px;
  display: flex;
  font-size: 14px;
  color: #333;

  .user-buy-set-label {
    margin-right: 10px;
    line-height: 32px;
  }

  .user-buy-set-box {
    .item-user-price-set {
      display: flex;
      align-items: center;

      &:not(:last-child) {
        margin-bottom: 12px;
      }
    }
  }
}

.rule-list-blank {
  height: 200px;
  width: 100%;
  font-size: 16px;
  color: #999;
  text-align: center;
  line-height: 200px;
}

.rule_list {
  width: 100%;

  .item_rule_box {
    border: 1px solid #eee;
    border-radius: 4px;

    &:not(:last-child) {
      margin-bottom: 16px;
    }

    .item_rule_top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 60px;
      background-color: #f3f3f3;
      padding: 0 24px;

      .item_rule_label {
        font-size: 16px;
        color: #333;
      }
    }

    .item_rule_content {
      background-color: #fff;
      padding: 16px 24px;

      .item_rule_content_show {
        display: flex;
        align-items: center;

        &:not(:last-child) {
          margin-bottom: 24px;
        }

        .item_rule_content_label {
          font-size: 14px;
          color: #333;
        }

        .item_rule_content_desc {
          flex: 1;
          overflow: hidden;
          font-size: 14px;
          color: #999;
          margin-left: 32px;
        }
      }
    }
  }
}
</style>
